//
//  ViewController1.swift
//  NetEaseBUFF
//
//  Created by QFX on 2023/10/27.
//

import SnapKit
import UIKit
import Alamofire
import MJRefresh
import SwiftyJSON
import SDWebImage
import MBProgressHUD
import MarqueeLabel
class ViewController1: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return self.list.count + 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            return 0
        }
        let item:JSON = self.list[section-1];
        let count = item["count"].int
        return count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cellIdentifier = "dataCollectionCell"
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! dataCollectionCell
        
        
        let section = indexPath.section
        let row = indexPath.row
        let data:JSON = self.list[section-1];
        let goods = data["goods"].array
        let sell_orders = data["sell_orders"].array
        let goods_infosDict = data["goods_infos"].dictionary
        let goods_item = goods?[row].dictionary
        let sell_orders_item = sell_orders?[row].dictionary
        let data_type = data["data_type"].stringValue
        let goods_id = String(format: "%ld", sell_orders_item?["goods_id"]?.int ?? 0)
        let sell_orders_info_item = goods_infosDict?[goods_id]?.dictionary
  
        if let item = goods_item {
            let name = item["name"]?.stringValue
            let sell_min_price = item["sell_min_price"]?.stringValue
            let sell_num = item["sell_num"]?.int
            let goods_info = item["goods_info"]?.dictionary
            let icon_url = goods_info?["icon_url"]?.stringValue
            let info = goods_info?["info"]?.dictionary
            let tags = info?["tags"]?.dictionary
            let exterior_localized_name = tags?["exterior"]?["localized_name"].stringValue
            let quality_localized_name = tags?["quality"]?["localized_name"].stringValue
            let rarity = tags?["rarity"]?["localized_name"].stringValue
            
            cell.saleLabel.text = String(format: "%d", sell_num ?? 0) + "件在售";
            cell.priceLabel.text = "￥" + String(format: "%@", sell_min_price ?? "")
            cell.nameLabel.text = name;
            cell.tipLabel.text = exterior_localized_name == nil ? (rarity != nil ? rarity : exterior_localized_name) : exterior_localized_name;
            cell.dataImageView.sd_setImage(with: URL.init(string: icon_url ?? ""))
            cell.tip1View.isHidden = exterior_localized_name == nil && rarity == nil
            cell.tip2View.isHidden = quality_localized_name == nil
            cell.tip2Label.text = quality_localized_name
            cell.tipLabel.textColor = (exterior_localized_name == "崭新出厂" ||  exterior_localized_name == "略有磨损") ? UIColor(hex: "#7EB173") :  exterior_localized_name == "久经沙场" ? UIColor(hex: "#7EB173") :   exterior_localized_name == "战痕累累" ? UIColor(hex: "#D9584D")   : rarity == "非凡" ? UIColor(hex: "#D9584D")   : rarity == "卓越" ? UIColor(hex: "#947DDD") : .white
            cell.tip2Label.textColor = quality_localized_name == "纪念品" ? UIColor(hex: "#EAE098") :  (quality_localized_name == "★ StatTrak™" || quality_localized_name == "★") ?  UIColor(hex: "#947DDD") : UIColor(hex: "#947DDD")
            cell.tipWidthConstraints.constant = exterior_localized_name?.count == 4 ? 56 : (exterior_localized_name?.count == 2 || rarity?.count == 2) ? 35 : 0
            cell.tip2WidthConstraints.constant = quality_localized_name?.count == 3 ? 40 : exterior_localized_name?.count == 2 ? 40 : quality_localized_name?.count == 1 ? 20 : 0
            cell.tip1View.backgroundColor = (cell.tipLabel.text == "崭新出厂" || cell.tipLabel.text == "略有磨损"  || cell.tipLabel.text == "久经沙场" || cell.tipLabel.text == "战痕累累" || cell.tipLabel.text == "非凡") ? UIColor(hex: "#D9584D")  : cell.tipLabel.text == "卓越" ? UIColor(hex: "#947DDD") : UIColor(hex: "#D9584D")
            cell.saleLabel.isHidden = false
            cell.paintwearView.isHidden = true
        }
 
        if let item = sell_orders_info_item {
            let name = item["name"]?.stringValue
            let sell_min_price = item["steam_price_cny"]?.stringValue
            let sell_num = item["sell_num"]?.int
            let icon_url = item["icon_url"]?.stringValue
            let tags = item["tags"]?.dictionary
            let exterior_localized_name = tags?["exterior"]?["localized_name"].stringValue
            let quality_localized_name = tags?["quality"]?["localized_name"].stringValue
            let rarity = tags?["rarity"]?["localized_name"].stringValue
            let asset_info = sell_orders_item?["asset_info"]?.dictionary
            let paintwear = asset_info?["paintwear"]?.stringValue
            let s = NSString(format: "%@", paintwear ?? "")
            
            cell.downLeftConstraint.constant = CGFloat(s.floatValue) * (KScreenWidth-30)/2
            cell.saleLabel.isHidden = sell_num == nil
            cell.saleLabel.text = String(format: "%d", sell_num ?? 0) + "件在售";
            cell.priceLabel.text = "￥" + String(format: "%@", sell_min_price ?? "")
            cell.nameLabel.text = name;
            cell.tipLabel.text = exterior_localized_name == nil ? (rarity != nil ? rarity : exterior_localized_name) : exterior_localized_name;
            cell.dataImageView.sd_setImage(with: URL.init(string: icon_url ?? ""))
            cell.tip1View.isHidden = exterior_localized_name == nil && rarity == nil
            cell.tip2View.isHidden = quality_localized_name == nil
            cell.tip2Label.text = quality_localized_name
            cell.tipLabel.textColor = (exterior_localized_name == "崭新出厂" ||  exterior_localized_name == "略有磨损") ? UIColor(hex: "#7EB173") :  exterior_localized_name == "久经沙场" ? UIColor(hex: "#7EB173") :   exterior_localized_name == "战痕累累" ? UIColor(hex: "#D9584D")   : rarity == "非凡" ? UIColor(hex: "#D9584D")   : rarity == "卓越" ? UIColor(hex: "#947DDD") : .white
            cell.tip2Label.textColor = quality_localized_name == "纪念品" ? UIColor(hex: "#EAE098") :  (quality_localized_name == "★ StatTrak™" || quality_localized_name == "★") ?  UIColor(hex: "#947DDD") : UIColor(hex: "#947DDD")
            cell.tipWidthConstraints.constant = exterior_localized_name?.count == 4 ? 56 : (exterior_localized_name?.count == 2 || rarity?.count == 2) ? 35 : 0
            cell.tip2WidthConstraints.constant = quality_localized_name?.count == 3 ? 40 : exterior_localized_name?.count == 2 ? 40 : quality_localized_name?.count == 1 ? 20 : 0
            cell.tip1View.backgroundColor = (cell.tipLabel.text == "崭新出厂" || cell.tipLabel.text == "略有磨损"  || cell.tipLabel.text == "久经沙场" || cell.tipLabel.text == "战痕累累" || cell.tipLabel.text == "非凡") ? UIColor(hex: "#D9584D")  : cell.tipLabel.text == "卓越" ? UIColor(hex: "#947DDD") : UIColor(hex: "#D9584D")
            cell.paintwearLabel.text = String(format: "磨损度: %@", paintwear ?? "")
            cell.paintwearView.isHidden = paintwear == nil
        }

        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView{
        var head:UICollectionReusableView?
        let section = indexPath.section
        if kind == UICollectionView.elementKindSectionHeader {
            if section == 0 {
                head  = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HeadReusableView", for: indexPath)
                return head!
            }else{
                let section = indexPath.section
                let row = indexPath.row
                let data:JSON = self.list[section-1];
               let headview = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HeaderTitleReusableView", for: indexPath) as! HeaderTitleReusableView
                let title = data["title"].stringValue
                headview.titleLabel?.text = title
                return headview
            }
 
        }
        return head!
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
        if section == 0 {
            return CGSize(width:collectionView.bounds.width , height: 200)
        }
        return CGSize(width:collectionView.bounds.width , height: 50)
    }
    
    
    public lazy var collectionView: UICollectionView = {
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize.init(width: (KScreenWidth-30)/2, height: 150)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.scrollDirection = .vertical
        
        let collectionView: UICollectionView = UICollectionView(frame:.zero, collectionViewLayout: layout)
        //        collectionView.showsHorizontalScrollIndicator = false
        //        collectionView.showsVerticalScrollIndicator = false
        collectionView.backgroundColor = UIColor.clear
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UINib(nibName: "dataCollectionCell", bundle: nil), forCellWithReuseIdentifier: "dataCollectionCell")
        collectionView.register(UINib(nibName: "HeadReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HeadReusableView")
        collectionView.register(UINib(nibName: "HeaderTitleReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HeaderTitleReusableView")
        return collectionView
    }()
    
 
    
 
    var list:[JSON] = []
 
    
    @objc func getDefalutData(){
        self.getData()
    }
    
    @objc func getMoreData(){
         self.getData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.

        self.getData()
        self.view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(88)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(-KUITabBarHeight)
        }
         let refreshHeader = MJRefreshStateHeader.init(refreshingTarget: self, refreshingAction:#selector(getDefalutData))
        refreshHeader.setTitle("", for: .pulling)
        refreshHeader.setTitle("", for: .refreshing)
        refreshHeader.setTitle("", for: .willRefresh)
        refreshHeader.lastUpdatedTimeLabel?.text = ""
         self.collectionView.mj_header = refreshHeader
        
        
        //        self.collectionView
        
    }
    
    func getData(){
        self.list.removeAll()
        if let path = Bundle.main.path(forResource:"index", ofType: "json"){
            if let data = NSData(contentsOfFile: path) as? Data{
                if let json = try?JSONSerialization.jsonObject(with: data , options: .mutableContainers){
                    let parseJson = JSON(json)
                    if  let list = parseJson["data"]["items"].array{
                        for index in 0 ..< list.count {
                            let dict = list[index]
                            self.list.append(dict)
                        }
                    }
                    self.collectionView.reloadData()
                    self.collectionView.mj_footer?.endRefreshing()
                    self.collectionView.mj_header?.endRefreshing()
                }
            }
        }
    }
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    
    
}
